<template>
  <div class="ward-handle">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="病房编号" prop="wardNo">
            <el-input v-model="form.wardNo" placeholder="请输入病房编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="病房名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入病房名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属科室" prop="departmentId">
            <el-tree-select
              v-model="form.departmentId"
              placeholder="请选择科室"
              style="width: 100%"
              :data="departmentTree"
              node-key="id"
              :props="{
                label: 'name',
                value: 'id',
                children: 'children'
              }"
              check-strictly
              clearable
              filterable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="病房类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
              <el-option label="普通病房" :value="1" />
              <el-option label="重症监护" :value="2" />
              <el-option label="手术室" :value="3" />
              <el-option label="产房" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="楼层" prop="floor">
            <el-input-number
              v-model="form.floor"
              :min="1"
              :max="50"
              placeholder="请输入楼层"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总床位数" prop="totalBeds">
            <el-input-number
              v-model="form.totalBeds"
              :min="1"
              :max="20"
              placeholder="请输入床位数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="已占用床位" prop="occupiedBeds">
            <el-input-number
              v-model="form.occupiedBeds"
              :min="0"
              :max="form.totalBeds || 20"
              placeholder="已占用床位数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责护士" prop="nurseId">
            <el-select
              v-model="form.nurseId"
              placeholder="请选择负责护士"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="nurse in nurseList"
                :key="nurse.id"
                :label="nurse.name"
                :value="nurse.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="位置描述" prop="location">
        <el-input v-model="form.location" placeholder="请输入位置描述" />
      </el-form-item>
      <el-form-item label="设备信息" prop="equipment">
        <el-input
          v-model="form.equipment"
          type="textarea"
          :rows="3"
          placeholder="请输入设备信息"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        确定
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'

// 定义props
const props = defineProps({
  wardData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  departmentList: {
    type: Array,
    default: () => []
  },
  nurseList: {
    type: Array,
    default: () => []
  }
})

// 定义emits  
const emit = defineEmits(['close'])

// 响应式数据
const formRef = ref(null)
const submitLoading = ref(false)
const departmentTree = ref([])

// 表单数据
const form = reactive({
  id: null,
  wardNo: '',
  name: '',
  departmentId: null,
  type: null,
  floor: null,
  totalBeds: null,
  occupiedBeds: 0,
  location: '',
  nurseId: null,
  equipment: '',
  remark: ''
})

// 表单验证规则
const rules = {
  wardNo: [
    { required: true, message: '请输入病房编号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入病房名称', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: '请选择所属科室', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择病房类型', trigger: 'change' }
  ],
  floor: [
    { required: true, message: '请输入楼层', trigger: 'blur' }
  ],
  totalBeds: [
    { required: true, message: '请输入总床位数', trigger: 'blur' }
  ]
}

// 获取科室树形数据
const getDepartmentTreeData = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 处理取消
const handleCancel = () => {
  emit('close')
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    const isEdit = !!form.id
    const url = '/admin/ward'
    const method = isEdit ? 'put' : 'post'
    
    const response = await request[method](url, form)
    
    if (response.code === 200) {
      ElMessage.success(isEdit ? '更新成功' : '添加成功')
      emit('close', 'success')
    } else {
      ElMessage.error(response.message || (isEdit ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  getDepartmentTreeData()
  if (props.isEdit && props.wardData) {
    Object.assign(form, props.wardData)
  }
})
</script>

<style scoped>
.ward-handle {
  padding: 20px 0;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}
</style> 